package com.yeskery.nut.web.demo.common;

import com.alibaba.fastjson2.JSON;
import com.yeskery.nut.annotation.bean.Autowired;
import com.yeskery.nut.annotation.bean.Component;
import com.yeskery.nut.bean.InitializingBean;
import com.yeskery.nut.core.RequestApplicationContext;
import com.yeskery.nut.extend.i18n.MessageService;
import com.yeskery.nut.extend.memory.Storage;
import com.yeskery.nut.util.StringUtils;
import com.yeskery.nut.web.demo.dto.UserDto;
import com.yeskery.nut.web.demo.exception.AuthException;

/**
 * 用户信息上下文
 * @author Yeskery
 * 2023/7/28
 */
@Component
public class UserContext implements InitializingBean {

    @Autowired
    private Storage injectStorage;

    @Autowired
    private MessageService injectMessageService;

    private static Storage storage;

    private static MessageService messageService;

    @Override
    public void initialize() throws Exception {
        storage = injectStorage;
        messageService = injectMessageService;
    }

    /**
     * 获取当前登录的用户信息
     * @return
     */
    public static UserDto getUser() {
        String token = RequestApplicationContext.getResource(Constants.AUTH_TOKEN_KEY, String.class);
        if (StringUtils.isEmpty(token)) {
            throw new AuthException(messageService.getMessage("token.missing"));
        }
        String value = storage.get(String.format(Constants.AUTH_TOKEN_REDIS_KEY, token), String.class);
        if (StringUtils.isEmpty(value)) {
            throw new AuthException(messageService.getMessage("token.invalid"));
        }
        return JSON.parseObject(value, UserDto.class);
    }

    /**
     * 获取当前登录的用户信息
     * @return
     */
    public static String getOAuthUserName() {
        return RequestApplicationContext.getResource(Constants.OAUTH_TOKEN_KEY, String.class);
    }
}
